SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
 
CREATE FUNCTION [Valcomm].[AssetHelper]
 (
 @ExportId INT
 )
 
 RETURNS TABLE
 
 AS
 RETURN

-- WITH FundedPortion AS (

--SELECT * FROM  FSFundModel_VALCOMM.dbo.Asset AS a 

--WHERE	a.FundCreditInstrumentId IS NOT NULL
--), 
--UnfundedPortion AS (
--SELECT * FROM FSFundModel_VALCOMM.dbo.Asset AS a WHERE a.AssetType <> 'Instrument'
--)
--, Combine AS (
--SELECT COALESCE(fp.AssetIntrnlId, a.assetIntrnlId) AssetIntrnlId, COALESCE(up.PurchDate, a.purchDate) OrigPurchDate

--FROM  FundedPortion fp  
--INNER JOIN UnfundedPortion up ON fp.InstrumentId = up.InstrumentId AND fp.PortfolioId =up.PortfolioId
--RIGHT JOIN FSFundModel_VALCOMM.dbo.Asset AS a
--ON a.AssetIntrnlId = fp.AssetIntrnlId
--)



SELECT  
       a.AssetIntrnlId,
	   a.ExportId,
		[tgpr].[NBSReason] AS NBSReason,
		ca.InstrName,
		ca.InstrClass, 
		ca.InstSortOrder,

    a.AssetType, tgpr.portfoliopurchase, [ca].[UnfundedbyPfSort],
		[tgpr].[OrigPurch] unfundedpurchdate
	--, comb.OrigPurchDate

        
FROM    [FSFundModel_VALCOMM].Reporting.Asset a
        INNER JOIN [FSFundModel_VALCOMM].Reporting.Instrument i ON a.ExportId = i.ExportId
                                                         AND a.InstrumentId = i.InstrumentId
        INNER JOIN FSFundModel_Valcomm.Reporting.InstrumentDefinition id ON i.InstDefId = id.InstDefId
                                                              AND a.ExportId = id.ExportId 
				INNER JOIN  [Valcomm].[tvfGetPropReason](@ExportId) tgpr
						ON [tgpr].[AssetIntrnlId] = [a].[AssetIntrnlId]
	--	INNER JOIN Combine comb ON comb.AssetIntrnlId = a.AssetIntrnlId
		
		CROSS APPLY (

			SELECT --Live.GetPropReason(@ExportId, a.AssetIntrnlId) 
			
							--Live.GetInstrumentName(@ExportId, a.AssetIntrnlId) 
			CASE WHEN a.AssetType <> 'Instrument' THEN i.InstrName + ' - ' + REPLACE(a.AssetType , 'DelayedDraw', 'Delayed Draw')
						ELSE i.InstrName
						END  AS InstrName, 
			--Live.GetInstrumentClass(@ExportId, a.AssetIntrnlId)  
			CASE WHEN a.AssetType <> 'Instrument' THEN 'Unfunded Positions' 
				ELSE id.InstrClass 
				END 
						AS InstrClass,
			--live.GetInstrumentSortOrder(@ExportId, a.AssetIntrnlId) 
			CASE WHEN a.AssetType <> 'Instrument' THEN 90 + id.SortOrder 
						ELSE id.SortOrder
						END 
						AS InstSortOrder
				, 	CASE WHEN a.AssetType <> 'Instrument' THEN .5 + id.SortOrder 
						ELSE id.SortOrder
						END 
						AS UnfundedbyPfSort
			) ca
WHERE   a.ExportId = @ExportId
        --AND a.IsActiveEndOfDay = 1 
GO
